<template>
  <div>
    <Row>
      <Col span="24">
        <Card class="margin-bottom-10">
          <Form inline>
            <FormItem class="margin-bottom-0">
              <Select
                v-model="searchConf.game_hash"
                filterable
                remote
                :remote-method="getGameName"
                style="width:260px"
                placeholder='请选择游戏'
                :loading="nameLoading"
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{option.label}}</Option>
              </Select>
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <div class="margin-bottom-15">
            <Button type="primary" v-has="'Gift/add'" @click="alertAdd" icon="md-add">{{ $t('add_button') }}</Button>
          </div>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover />
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total />
          </div>
        </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>{{formItem.id ? '编辑' : '新增'}}礼包</span>
      </p>
      <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="100">
        <Row>
          <Col span="12">
            <FormItem label="目标游戏" prop="game_hash">
              <Select
                v-model="formItem.game_hash"
                filterable
                style="width: 100%"
                placeholder='请选择游戏'
                :disabled="formItem.id !== 0"
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{option.label}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="领取限制" prop="type">
              <Select
                v-model="formItem.type"
                filterable
                style="width: 100%"
                placeholder='请选择领取限制'
              >
                <Option value="1">单次领取</Option>
                <Option value="2">多次领取</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="礼包名称" prop="title">
              <Input v-model="formItem.title" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="发送人" prop="send">
              <Input v-model="formItem.send" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="永久KEY" prop="keys">
              <Input v-model="formItem.keys" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="KEY领取次数" prop="keys_number">
              <Input v-model="formItem.keys_number" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="vip限制" prop="keys">
              <Input-number v-model="formItem.vip" number />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="礼包介绍" prop="info">
          <Input v-model="formItem.info" type="textarea" :autosize="{minRows: 5,maxRows: 8}" />
        </FormItem>
        <FormItem label="礼包奖品" prop="reward">
          <Input v-model="formItem.reward" type="textarea" :autosize="{minRows: 5,maxRows: 8}" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" class="margin-right-10">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="keySetting.show" width="996" :styles="{top: '30px'}">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>获取礼包码</span>
      </p>
      <div class="margin-bottom-15" v-has="'Gift/buildCode'">
        <Input v-model="buildKeyInfo.number" placeholder="请输入生成礼包码的数量" class="margin-right-10" style="width: 200px" />
        <Button type="primary" @click="buildCdKeys" icon="md-add">生成</Button>
      </div>
      <div class="margin-bottom-15" style="width:37%;display: flex;justify-content: space-around;">
        <Input v-model="buildKeyInfo.openid" placeholder="请输入openid" class="margin-right-10" style="width: 200px" />
        <Button type="primary" @click="getKeyList">查询</Button>
        <Button type="warning" @click="download">导出</Button>
      </div>
      <div>
        <Table :loading="keySetting.listLoading" :columns="keyColumnsList" :data="keyData" border disabled-hover />
      </div>
      <div slot="footer" style="text-align: center">
        <Page :total="keyShow.listCount" :current="keyShow.currentPage" :page-size="keyShow.pageSize"
              @on-change="changeKeyPage" @on-page-size-change="changeKeySize" show-elevator show-sizer show-total />
      </div>
    </Modal>
  </div>
</template>
<script>
import { getList, add, edit, del, code, buildCode, exportCode } from '@/api/game-gift'
import { getChoose } from '@/api/game-manager'

const editButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.edit) {
    return h('Button', {
      props: {
        type: 'primary'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.getGameName()
          vm.formItem.id = currentRow.id
          vm.formItem.keys = currentRow.keys
          vm.formItem.keys_number = currentRow.keys_number
          vm.formItem.title = currentRow.title
          vm.formItem.game_hash = currentRow.game_hash
          vm.formItem.info = currentRow.info
          vm.formItem.reward = currentRow.reward
          vm.formItem.vip = currentRow.vip
          vm.formItem.type = currentRow.type.toString()
          vm.modalSetting.show = true
          vm.modalSetting.index = index
        }
      }
    }, vm.$t('edit_button'))
  }
}
const deleteButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.del) {
    return h('Poptip', {
      props: {
        confirm: true,
        title: '您确定要删除这条数据吗? ',
        transfer: true
      },
      on: {
        'on-ok': () => {
          let params = {
            id: currentRow.id,
            game_hash: currentRow.game_hash
          }
          del(params).then(response => {
            vm.tableData.splice(index, 1)
            vm.$Message.success(response.data.msg)
          })
          currentRow.loading = false
        }
      }
    }, [
      h('Button', {
        style: {
          margin: '0 5px'
        },
        props: {
          type: 'error',
          placement: 'top',
          loading: currentRow.isDeleting
        }
      }, vm.$t('delete_button'))
    ])
  }
}
const keyButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.key) {
    return h('Button', {
      props: {
        type: 'warning'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.buildKeyInfo.gift_bag_id = currentRow.id
          vm.buildKeyInfo.game_hash = currentRow.game_hash
          vm.getKeyList()
          vm.keySetting.show = true
          vm.keySetting.index = index
        }
      }
    }, '礼包码')
  }
}

export default {
  name: 'operate-gift',
  data () {
    return {
      nameLoading: false,
      gameNameOption: [],
      gameShow: {},
      columnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '礼包名称',
          align: 'center',
          key: 'title',
          tooltip: true,
          width: 200
        },
        {
          title: '永久KEY',
          align: 'center',
          key: 'keys',
          minWidth: 260
        },
        {
          title: 'KEY领取次数',
          align: 'center',
          key: 'keys_number',
          minWidth: 160
        },
        {
          title: '等级限制',
          align: 'center',
          key: 'vip',
          minWidth: 100
        },
        {
          title: '事件描述',
          align: 'center',
          key: 'info',
          tooltip: true,
          width: 200
        },
        {
          title: '礼包奖励',
          align: 'center',
          key: 'reward',
          tooltip: true,
          width: 200
        },
        {
          title: '所属游戏',
          align: 'center',
          render: (h, params) => {
            return h('span', this.gameShow[params.row.game_hash])
          },
          width: 200
        },
        {
          title: '操作',
          align: 'center',
          width: 300,
          render: (h, params) => {
            return h('div', [
              keyButton(this, h, params.row, params.index),
              editButton(this, h, params.row, params.index),
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      tableData: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        game_hash: ''
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      formItem: {
        title: '',
        keys: '',
        keys_number: 0,
        vip: 0,
        game_hash: '',
        reward: '',
        type: '1',
        info: '',
        send: '系统',
        id: 0
      },
      ruleValidate: {
        title: [
          { required: true, message: '礼包名称不能为空', trigger: 'blur' }
        ],
        game_hash: [
          { required: true, message: '请选择游戏', trigger: 'blur' }
        ]
      },
      buttonShow: {
        edit: true,
        del: true,
        key: true
      },

      keySetting: {
        show: false,
        loading: false,
        listLoading: false,
        index: 0
      },
      keyColumnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: 'CD-KEY',
          align: 'center',
          key: 'key',
          tooltip: true,
          width: 200
        },
        {
          title: '使用者',
          align: 'center',
          key: 'openid',
          render: (h, params) => {
            if (params.row.openid) {
              return h('span', params.row.openid)
            } else {
              return h('span', '-')
            }
          },
          minWidth: 260
        },
        {
          title: '使用角色ID',
          align: 'center',
          key: 'role_id',
          render: (h, params) => {
            if (params.row.role_id) {
              return h('span', params.row.role_id)
            } else {
              return h('span', '-')
            }
          },
          minWidth: 160
        },
        {
          title: '兑换时间',
          align: 'center',
          render: (h, params) => {
            if (params.row.uid) {
              return h('span', params.row.updated_at)
            } else {
              return h('span', '-')
            }
          },
          width: 200
        }
      ],
      keyData: [],
      keyShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      buildKeyInfo: {
        number: '',
        game_hash: '',
        gift_bag_id: 0,
        openid: ''
      },

      listLoading: false
    }
  },
  created () {
    let vm = this
    vm.getList()
    vm.hasRule('Gift/edit').then(res => {
      vm.buttonShow.edit = res
    })
    vm.hasRule('Gift/del').then(res => {
      vm.buttonShow.del = res
    })
    vm.getGameName()
  },
  methods: {
    alertAdd () {
      this.getGameName()
      this.modalSetting.show = true
    },
    getKeyList () {
      let vm = this
      vm.keySetting.listLoading = true
      code({
        page: vm.keyShow.currentPage,
        size: vm.keyShow.pageSize,
        gift_bag_id: vm.buildKeyInfo.gift_bag_id,
        game_hash: vm.buildKeyInfo.game_hash,
        openid: vm.buildKeyInfo.openid
      }).then(response => {
        vm.keyData = response.data.data.list
        vm.keyShow.listCount = response.data.data.count
        vm.keySetting.listLoading = false
      })
    },
    download () {
      if (this.buildKeyInfo.gift_bag_id === '' || this.buildKeyInfo.openid) {
        return
      }
      let d = new Date(new Date().getTime())
      let date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
      let fileName = `礼包码-${date}.xlsx`
      exportCode({
        gift_bag_id: this.buildKeyInfo.gift_bag_id,
        openid: this.buildKeyInfo.openid
      }).then(response => {
        if (response.data.byteLength === 31) {
          this.$Message.error('导出失败,暂无数据')
          return
        }
        if (response.data.byteLength === 32) {
          this.$Message.error('导出失败,数据超过1000条,请联系管理员')
          return
        }
        const data = new Blob([response.data], { type: 'application/octet-stream' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE workaround
          window.navigator.msSaveBlob(data, fileName)
        } else {
          // Other browsers
          const url = window.URL.createObjectURL(data)
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
      })
    },
    buildCdKeys () {
      let vm = this
      if (vm.buildKeyInfo.number) {
        buildCode(vm.buildKeyInfo).then(response => {
          vm.tableData = response.data.data.list
          vm.tableShow.listCount = response.data.data.count
          vm.buildKeyInfo.number = ''
          vm.getKeyList()
        })
      }
    },

    changeKeyPage (page) {
      this.keyShow.currentPage = page
      this.getKeyList()
    },
    changeKeySize (size) {
      this.keyShow.pageSize = size
      this.getKeyList()
    },

    getGameName (value) {
      if (!this.gameNameOption.length) {
        getChoose({
          keyword: value
        }).then(response => {
          this.gameNameOption = response.data.data.list
          this.gameNameOption.forEach(i => {
            this.gameShow[i.value] = i.label
          })
        })
      }
    },
    submit () {
      let vm = this
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          vm.modalSetting.loading = true
          if (vm.formItem.id === 0) {
            add(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          } else {
            edit(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          }
        }
      })
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.formItem.type = '1'
        this.formItem.keys_number = 0
        this.formItem.vip = 0
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        ...vm.searchConf
      }
      vm.listLoading = true
      getList(params).then(response => {
        vm.tableData = response.data.data.list
        vm.tableShow.listCount = response.data.data.count
        vm.listLoading = false
      })
    }
  }
}
</script>
